package com.zhang.boot.core.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.zhang.boot.core.service.OSSService;
import com.zhang.boot.core.vo.Result;
import com.zhang.boot.core.vo.oss.PolicyInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * @Author zhangshaobin
 * @Date 2020/11/10
 * @Description
 */
@Service
@RequiredArgsConstructor
public class OSSServiceImpl implements OSSService {

    private final OSS ossClient;

    @Value("${oss.access-key}")
    private String accessId;
    @Value("${oss.endpoint}")
    private String endpoint;
    @Value("${oss.bucket}")
    private String bucket;

    @Override
    public Result getPolicy() {
        String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint
        String dir = "article/images/"; // 用户上传文件时指定的前缀。
        long expireTime = 30;
        long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
        Date expiration = new Date(expireEndTime);
        // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
        PolicyConditions policyConds = new PolicyConditions();
        policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
        policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
        String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
        byte[] binaryData = new byte[0];
        try {
            binaryData = postPolicy.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String encodedPolicy = BinaryUtil.toBase64String(binaryData);
        String postSignature = ossClient.calculatePostSignature(postPolicy);
        PolicyInfo policyInfo = PolicyInfo.builder()
                .accessid(accessId)
                .policy(encodedPolicy)
                .signature(postSignature)
                .dir(dir)
                .host(host)
                .expire(expireEndTime / 1000)
                .build();
        return Result.ok(policyInfo);
    }
}
